package service

import (
	"context"
	"database/sql"

	"gitee.com/WisdomClassroom/ClassStruct/glb"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"google.golang.org/grpc/metadata"
)

func (s *Service) CreateClass(ctx context.Context, request *pb.CreateClassRequest) (*pb.CreateClassResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.CreateClassResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	if !token.IsManager && token.Type != core.UserTypeTeacher {
		return &pb.CreateClassResponse{Status: &pb.ResponseStatus{
			Code:    core.ResponseStatusCodeNotAuth,
			Message: "用户没有权限",
		}}, nil
	}

	class := &models.ClassModel{
		Name:        sql.NullString{String: request.GetName(), Valid: true},
		Description: sql.NullString{String: request.GetDescription(), Valid: true},
		CourseUUID:  sql.NullString{String: request.GetCourseUUID(), Valid: true},
		CreatorID:   sql.NullInt32{Int32: token.AccountID, Valid: true},
	}
	err = glb.DB.Create(class).Error
	if err != nil {
		if core.IsForeignKeyErr(err) {
			return &pb.CreateClassResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "课程不存在",
			}}, nil
		} else if core.IsDuplicateKeyErr(err) {
			return &pb.CreateClassResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "此班级名称已存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return createClassRespSvrErr, nil
	}

	return &pb.CreateClassResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
		UUID:   class.UUID,
	}, nil
}
